<template>
  <el-dialog :title="title"
             :visible.sync="visible"
             width="480px"
             :before-close="handleClose">
    <el-form :model="createForm"
             :rules="rules"
             ref="createForm"
             label-width="110px">
      <el-form-item label="姓名"
                    style="text-align: left;"
                    prop="name">
        <el-input v-model="createForm.name"
                  placeholder="请输入回收员姓名"
                  style="width: 216px" />
      </el-form-item>
      <el-form-item label="手机号码"
                    style="text-align: left;"
                    prop="phone">
        <el-input v-model="createForm.phone"
                  placeholder="请输入回手机号码"
                  style="width: 216px" />
      </el-form-item>
      <el-form-item label="设置密码"
                    style="text-align: left;"
                    prop="password">
        <el-input v-model="createForm.password"
                  placeholder="请输入登录密码"
                  style="width: 216px" />
      </el-form-item>
      <el-form-item label="性别"
                    style="text-align: left"
                    prop="sex">
        <el-radio v-model="createForm.sex"
                  :label="1">男</el-radio>
        <el-radio v-model="createForm.sex"
                  :label="0">女</el-radio>
        <el-radio v-model="createForm.sex"
                  :label="2">保密</el-radio>
      </el-form-item>
      <el-form-item label="回收站地址"
                    style="text-align: left"
                    prop="address">
        <el-cascader :options="options"
                     v-model="createForm.addressCode"
                     clearable
                     @change="handleChangeCity"></el-cascader>
      </el-form-item>
      <el-form-item label="详细回收地址"
                    prop="details">
        <el-input v-model="createForm.details"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入详细回收站地址" />
      </el-form-item>
    </el-form>
    <span slot="footer"
          class="dialog-footer">
      <el-button :disabled="loading" @click="handleClose">取 消</el-button>
      <el-button :loading="loading" type="primary"
                 @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import cityData from '@/utils/city'
import { createRecycle, queryUserDetails, updateRecycle } from '@/api'

export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: cityData,
      createForm: {
        name: undefined,
        phone: undefined,
        password: undefined,
        sex: 1,
        address: undefined,
        addressCode: undefined,
        details: undefined,
        provinceName: undefined,
        cityName: undefined,
        districtName: undefined
      },
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blue' },
          { min: 2, max: 10, message: '姓名长度为2-10位字符', trigger: 'blue' }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blue' },
          { pattern: /^\d{11}$/, message: '手机号码格式错误', trigger: 'blue' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blue' },
          { min: 6, max: 16, message: '密码长度为6- 16位字符', trigger: 'blue' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blue' }],
        address: [
          { required: true, message: '请选择回收站地址', trigger: 'blue' }
        ],
        details: [
          { required: true, message: '请输入详细回收地址', trigger: 'blue' }
        ]
      }
    }
  },
  watch: {
    visible(val) {
      const { id } = this.$route.query
      id && this.getUserInfo()
    }
  },
  methods: {
    // 取消
    handleClose() {
      this.$refs.createForm.clearValidate()
      this.$emit('close')
    },
    // 查询回收人员信息
    getUserInfo() {
      const { id } = this.$route.query
      queryUserDetails({ id }).then(res => {
        if (res.status === 200) {
          this.createForm.name = res.data.name
          this.createForm.phone = res.data.phone
          this.createForm.sex = res.data.sex
          this.createForm.address = res.data.address.split(',')
          this.createForm.addressCode = res.data.addressCode.split(',').map(item => Number(item))
          this.createForm.details = res.data.detailAddress
          this.createForm.provinceName = res.data.address[0]
          this.createForm.cityName = res.data.address[1]
          this.createForm.districtName = res.data.address[2]
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 获取城市文本
    getCascaderObj(val, opt) {
      //   const _self = this
      let provinceName
      let cityName
      let districtName
      opt.map(item => {
        if (item.value === val[0]) {
          provinceName = item.label
          item.children.map(k => {
            if (k.value === val[1]) {
              cityName = k.label
              k.children.map(m => {
                if (m.value === val[2]) {
                  districtName = m.label
                }
              })
            }
          })
        }
      })
      return [provinceName, cityName, districtName]
    },
    // 改变城市
    handleChangeCity(e) {
      if (e.length) {
        this.createForm.address = this.getCascaderObj(e, this.options)
      } else {
        this.createForm.address = undefined
      }
    },
    // 确认
    handleConfirm() {
      this.$refs.createForm.validate(valid => {
        if (valid) {
          this.loading = true
          const { id } = this.$route.query
          const params = {
            detailAddress: this.createForm.details,
            id: id || undefined,
            name: this.createForm.name,
            password: this.createForm.password,
            phone: this.createForm.phone,
            sex: this.createForm.sex,
            type: 2,
            addressCode: this.createForm.addressCode.join(),
            address: this.createForm.address.join()
          }
          id ? this.changeUserInfo(params) : this.createUser()
        }
      })
    },
    // 添加用户
    createUser(params) {
      createRecycle(params)
        .then(res => {
          this.loading = false
          this.$message.success('保存成功')
          this.$refs.createForm.resetFields()
          this.$emit('confirm')
        })
        .catch(() => {
          this.loading = false
          this.$message.error('保存失败')
        })
    },
    // 修改用户
    changeUserInfo(params) {
      updateRecycle(params).then(res => {
        if (res.status === 200) {
          this.loading = false
          this.$message.success('修改成功')
          this.$emit('confirm')
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.loading = false
        this.$message.error('修改失败')
      })
    }
  }
}
</script>
<style lang="scss">
.el-textarea__inner {
  resize: none;
}
</style>
